/*
 * @ author manma 
 * @ use  七牛云对象存储实现，用于文件上传
 */
const qiniu = require('qn');
const path = require('path');
const md5 = require('md5');
const config = require('../../config/config');
const Utils = require('../controllers/utils');
const globalConfig = config[process.env.NODE_ENV || 'development'];
class qiniuController {
	 constructor() {
	 	const qnconfig = globalConfig.qiniu;
        let _this = this
        Utils.getPrameter().then(_SYS =>{
            // console.log(res)
            if(!_SYS){
                console.log('请先运行在浏览器里运行http://localhost:8088/import导入基础数据')
            }else{
                _this.client = qiniu.create({
                    accessKey: _SYS.qiniu.access_key,
                    secretKey: _SYS.qiniu.secret_key,
                    bucket: _SYS.qiniu.bucket,
                    origin: _SYS.qiniu.bucket_url,
                });
            }
        })
    }
    qiniuPrameter(filePaths) {
        // key 为上传到七牛云后自定义图片的名称
        return new Promise((resolve, reject) => {
            let fileName = path.win32.basename(filePaths);
            let reg = /.(\.gif|\.jpeg|\.png|\.jpg|\.bmp)/i;
            let _fileName = fileName.split(reg)
            var hashName = md5(_fileName[0]);
            this.client.uploadFile(filePaths, { key: "/images/" + hashName + _fileName[1] }, function(err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    }
}

export default new qiniuController;